﻿using Consul;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using WesleyRedis;

namespace ConsulRegister
{
    /// <summary>
    /// 服务发现
    /// </summary>
    public class DiscoverServiceHelper : IDiscoverServiceHelper
    {
        public ConsulClient _consulClient;

        public DiscoverServiceHelper()
        {
            _consulClient = new ConsulClient(c => { c.Address = new Uri("http://localhost:8500"); });
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceNames"></param>
        /// <param name="isHttps"></param>
        public void GetServices(string[] serviceNames, bool isHttps)
        {
            Array.ForEach(serviceNames, serviceName =>
            {
                Task.Run(async () =>
                {
                    //WaitTime默认为5分钟
                    var queryOptions = new QueryOptions { WaitTime = TimeSpan.FromMinutes(5) };
                    await GetService(queryOptions, serviceName, isHttps);
                });
            });
        }

        /// <summary>
        /// 获取服务列表
        /// </summary>
        /// <param name="queryOptions"></param>
        /// <param name="serviceName"></param>
        /// <param name="isHttps"></param>
        /// <returns></returns>
        private Task<bool> GetService(QueryOptions queryOptions, string serviceName, bool isHttps)
        {
            var services = _consulClient.Health.Service(serviceName, string.Empty, true, queryOptions).Result;
            //版本号不一致 说明服务列表发生了变化
            if (services.Response.Length != 0 && services.LastIndex != queryOptions.WaitIndex)
            {
                var list = new List<string>();
                var http = isHttps ? "https" : "http";
                foreach (var item in services.Response)
                {
                    list.Add($"{http}://{item.Service.Address}:{item.Service.Port}");
                }
                RedisClient.RedisCt.SetStringKey(serviceName, list, TimeSpan.FromMinutes(60));
                Console.WriteLine($"queryOptions:{services.LastIndex }");
            }
            return Task.FromResult(true);
        }
    }
}